// import React from 'react'
import "./index.scss"
import { useNavigate } from "react-router"
import useSendMessage from "../../utils/index"
import { fetchCode, fetchLogin } from "../../api/login"
import { Button, Form, Input, Card, message, Space } from "antd"
import { useContext } from "react"
import { AuthContext } from '../../store';

export default function Login() {
const { setIsAuthenticated } = useContext(AuthContext);

  const navigate = useNavigate()

  const [count, flag, countDown] = useSendMessage(10)

  const [form] = Form.useForm()
  const getCode = async () => {
    const mobile = form.getFieldValue("mobile")
    if (mobile) {
      countDown()
      await fetchCode(mobile)
    } else {
      message.error("请先输入手机号")
    }
  }

  const goToLogin = async value => {
    const code = form.getFieldValue("code")

    if (code) {
      const res = await fetchLogin(value)

      //有才存，否则存上一个undefined会报错
      if (res) {
        localStorage.setItem("userInfo", JSON.stringify(res))
        message.success("登录成功，欢迎")
        setIsAuthenticated(true)
        navigate("/home")
      }
      else{
        message.error("验证码或手机号错误")
      }
    } else {
      message.error("请输入验证码")
    }
  }
  return (
    <div id="container">
      <Card className="login_card">
        <Form onFinish={goToLogin} form={form}>
          <Form.Item>
            <div
              style={{
                textAlign: "center",
                fontSize: "25px",
                color: "white",
                fontFamily: "fantasy",
              }}
            >
              Login
            </div>
          </Form.Item>
          <Form.Item name="mobile">
            <Input placeholder="请输入手机号"></Input>
          </Form.Item>
          <Form.Item name="code">
            <Space align="center" direction="horizontal" size="large">
              <Input placeholder="请输入验证码"></Input>
              <Button onClick={getCode} disabled={flag}>
                {flag ? count + "秒后再次发送" : "点击发送验证码"}
              </Button>
            </Space>
          </Form.Item>
          <Form.Item>
            <Button htmlType="submit" type="primary" ghost block>
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}
